import axios from "axios";
const service = axios.create({
  // baseURL: process.env.VUE_APP_BASE_URL,
  timeout: 50000000,
  withCredentials: true,
});
function getQueryString(name) {
	var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
	var r = window.location.search.substr(1).match(reg);

	if (r != null) {
		return unescape(r[2])
	};
	return null
}
service.interceptors.request.use(
	(request) => {
	  let companyUuid = getQueryString('companyUuid')
	  //绑定登陆ID
	  var userId=window.localStorage.getItem("2_userId");  
	  var requestBody=request.data;
	  if(requestBody && requestBody.params){
		if (userId && request.url.indexOf("getLogo") == -1 && request.url.indexOf("login") == -1) {
            requestBody.params.userId=userId;
		}
		if(request.url.indexOf("loginOut")!=-1){
			requestBody.params.userId=userId;
		}
		requestBody.params.loginType = "2";
	  }
	  request.headers={...request.headers,'userId':userId,'companyUuid':companyUuid,'loginType':'2'}
	  return request;
	},
	(err) => {
	  return Promise.reject(err);
	}
);
  // 添加响应拦截器
service.interceptors.response.use(  
	function(response) {
	  //验证登陆
	  var isLogin = window.localStorage["2_isLogin"];
	  if(response.status!==200 && isLogin == "true"){
		router.replace({
		  path: '/login'
		});
		window.localStorage.removeItem("2_isLogin");
			window.localStorage.removeItem("2_userId");
		return;
	  }
	  // console.log(response,88);
	  if(isLogin == "true") {
		const data = response.data
		if(typeof(data) == 'string') {
		  if (data == "") {
			router.replace({
				path: '/login'
			});
			window.localStorage.removeItem("2_isLogin");
			window.localStorage.removeItem("2_userId");
			return;
		  } else {
			var responseBody = JSON.parse(data);
			var result = responseBody.result;
			if(result == "-1") {
			  router.replace({
				  path: '/login'
			  });
			  window.localStorage.removeItem("2_isLogin");
			window.localStorage.removeItem("2_userId");
			  return;
			}
		  }
		}else if(typeof(data) == 'object'){
		  if(result == "-1") {
			router.replace({
			  path: '/login'
			});
			return;
		  }
		}
	  }
	  response.body=response.data
	  return response;
	},
	function(error) {    
	  return Promise.reject(error);
	}
);
export default service